package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.common.UserHolder;
import com.itheima.ydd.dto.CateDto;
import com.itheima.ydd.entity.*;
import com.itheima.ydd.service.*;
import com.itheima.ydd.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 后台管理
 */
@RestController
@Slf4j
@RequestMapping("index")
public class IndexController {

    @Autowired
    private UserService userService;

    @Autowired
    private ConfigService configService;

    @Autowired
    private AdvimgService advimgService;

    @Autowired
    private AdvposService advposService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CateService cateService;

    @Autowired
    private YddUserService yddUserService;

    /**
     * 用户登录
     * @param user
     * @return
     */

    @PostMapping("login")
    public ResultData login(@RequestBody User user) {
        log.info("用户信息: 邮箱:{},密码:{}", user.toString());

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getLogin_name, user.getLogin_name());
        queryWrapper.eq(User::getPassword, DigestUtils.md5Hex(user.getPassword()));
        User loginUser = userService.getOne(queryWrapper);

        if (loginUser == null) {
            throw new BusinessException("登录失败!");
        }

        Map retMap = new HashMap();
        Map tokenMap = new HashMap<>();
        // 登录成功
        if (loginUser != null) {
            // 生成token信息
            String roleId = loginUser.getRole_id()
                    .replace("[", "")
                    .replace("]", "")
                    .replace("\"", "");

            tokenMap.put("id", loginUser.getId());
            tokenMap.put("roleId", roleId);

            String token = JwtUtils.getToken(tokenMap);
            retMap.put("token", token);
        }
        return ResultData.ok("", retMap);
    }

    /**
     * 获取系统配置
     *
     * @return
     */
    @GetMapping("getConfig")
    public ResultData getConfig() {
        List<Config> list = configService.list();

        Map<String, String> map = new HashMap<>();
        for (Config config : list) {
            map.put(config.getAttr_key(), config.getAttr_value());
        }
        return ResultData.ok("", map);
    }

    /**
     * 获取用户资料
     *
     * @param
     * @return
     */
    @PostMapping("profile")
    public ResultData profile() {
        Map<String, Object> map = configService.profile();
        return ResultData.ok("", map);
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public void logout() {
        //删除用户信息
        UserHolder.remove();
    }

    //内容展示
    @GetMapping("/baseInfo")
    public ResultData getBaseInfo(){
        HashMap<String, Object> map = new HashMap<>();
        //获取管理账户数量
        int count = userService.count();
        map.put("admin_num",count);
        //获取广告图数量
        int count1 = advimgService.count();
        map.put("advimg_num",count1);
        //获取广告位数量
        int count2 = advposService.count();
        map.put("advpos_num",count2);
        //获取文章数量
        int count3 = articleService.count();
        map.put("article_num",count3);
        //获取分类文章数据
        List<Cate> cates = cateService.list();
        List<CateDto> list = cates.stream().map((cate) -> {
            CateDto cateDto = new CateDto();
            cateDto.setId(cate.getId());
            cateDto.setCatename(cate.getCateName());
            cateDto.setNum(cate.getSortNum());
            return cateDto;
        }).collect(Collectors.toList());
        map.put("all_cate",list);
        //获取点赞文章排行
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getLovenum);
        Page<Article> articlePage = new Page<>(1,7);
        articleService.page(articlePage,queryWrapper);
        map.put("hot_article",articlePage.getRecords());
        //获取注册的新用户
        Page<YddUser> userPage = new Page<>(1,7);
        yddUserService.page(userPage);
        map.put("new_user",userPage.getRecords());
        //获取用户性别
        HashMap<String,Integer> user = new HashMap<>();
        int count4 = yddUserService.count();
        int count5 = yddUserService.count(new LambdaQueryWrapper<YddUser>().eq(YddUser::getSex, 0));
        user.put("total",count4);
        user.put("user_man",count5);
        user.put("user_woman",(count4 -count5));
        map.put("user",user);

        return ResultData.ok("",map);
    }
}
